package com.qst.crop.controller;

import com.github.pagehelper.PageInfo;
import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.entity.Discuss;
import com.qst.crop.entity.Knowledge;
import com.qst.crop.security.entity.JwtUser;
import com.qst.crop.security.service.JwtUserDetailsServiceImpl;
import com.qst.crop.service.DiscussService;
import com.qst.crop.service.KnowledgeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@Slf4j
@Api("农业知识相关接口")
@RequestMapping("/knowledge")
public class KnowledgeController {

    @Autowired
    private KnowledgeService knowledgeService;
    @Autowired
    private DiscussService discussService;

    /**
     * @Description : 分页查询
     *  * @param pageNum
     * @Return : com.qst.crop.common.Result<com.github.pagehelper.PageInfo>
     */
    @ApiOperation("分页查询")
    @GetMapping("{pageNum}")
    public Result<PageInfo> page(@PathVariable Integer pageNum) {
        log.info("Knowledge Page {}", pageNum);

        PageInfo<Knowledge> pageInfo = knowledgeService.findAll(pageNum);
        return new Result<>(true, StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     * @Description : 根据id查询知识
     *  * @param id
     * @Return : com.qst.crop.common.Result<com.qst.crop.entity.Knowledge>
     */
    @ApiOperation("根据id查询知识")
    @GetMapping("/selectById/{id}")
    public Result<Knowledge> findById(@PathVariable Integer id) {
        log.info("根据id查询知识");

        Knowledge knowledge = knowledgeService.findById(id);
        return new Result<>(true, StatusCode.OK,"查询成功",knowledge);
    }

    /**
     * @Description : 根据条件查询知识
     *  * @param condition
     * @param pageNum
     * @Return : com.qst.crop.common.Result<com.github.pagehelper.PageInfo>
     */
    @ApiOperation("根据条件查询知识")
    @GetMapping("/{condition}/{pageNum}")
    public Result<PageInfo> findByWord(@PathVariable String condition,@PathVariable int pageNum) {
        log.info("根据条件查询知识");

        PageInfo<Knowledge> pageInfo = knowledgeService.findByCondition(condition,pageNum);
        return new Result<>(true, StatusCode.OK,"查询成功",pageInfo);
    }

    /**
     * @Description : 添加农业知识
     *  * @param knowledge
     * @Return : com.qst.crop.common.Result
     */
    @PostMapping
    @ApiOperation("添加农业知识")
    public Result save(@RequestBody Knowledge knowledge) {
        log.info("添加农业知识");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        knowledge.setOwnName(username);
        knowledge.setCreateTime(LocalDateTime.now());
        knowledge.setUpdateTime(LocalDateTime.now());
        knowledgeService.save(knowledge);
        return new Result<>(true, StatusCode.OK,"添加成功");
    }

    /**
     * @Description : 修改农业知识
     *  * @param knowledge
     * @Return : com.qst.crop.common.Result
     */
    @PutMapping("/{id}")
    @ApiOperation("修改农业知识")
    public Result update(@RequestBody Knowledge knowledge,@PathVariable("id") Integer id) {
        log.info("修改农业知识");
        knowledge.setKnowledgeId(id);
        knowledge.setUpdateTime(LocalDateTime.now());
        knowledgeService.update(knowledge);
        return new Result<>(true, StatusCode.OK,"修改成功");
    }

    @GetMapping("/selectByUsername")
    @ApiOperation("通过用户名获取")
    public Result<List<Knowledge>> findByUserName() {
        log.info("通过用户名获取");
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        log.info("888888888888888888888888888888888888888888888888888=" + username);

        List<Knowledge> knowledge = knowledgeService.getByUserName(username);
        return new Result<>(true, StatusCode.OK,"通过用户名查询成功",knowledge);
    }

    /**
     * @Description : 删除知识
     *  * @param id
     * @Return : com.qst.crop.common.Result
     */
    @DeleteMapping("{id}")
    @ApiOperation("删除知识")
    public Result delete(@PathVariable Integer id){
        log.info("删除知识");

        knowledgeService.deleteById(id);
        return new Result<>(true,StatusCode.OK,"删除成功");
    }

    @GetMapping("/debug")
    public String debugPage() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return "Authentication is null";
        } else if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return "Logged in as: " + userDetails.getUsername();
        } else {
            return "Logged in as: " + authentication.getPrincipal().toString();
        }
    }



    //TODO
    //接口正确，页面不显示

    /**
     * id查看知识评论
     * @param kId
     * @return
     */
    @ApiOperation("id查看知识评论")
    @GetMapping("/selectByKnowledge/{kId}")
    public Result<List<Discuss>> selectByKonwledge(@PathVariable("kId")Integer kId){
        return new Result<>(true, StatusCode.OK,"查询成功",discussService.selectByKonwledge(kId));
    }

    @GetMapping("/selAll")
    public List<Discuss> selectAllDiscuss(){
        return discussService.selectAllDiscuss();
    }


    @PostMapping("/addByKnowledge/{kId}/{content}")
    public Result<Discuss> addByKnowledge(@PathVariable("kId") Integer kid,@PathVariable("content")String content){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser principal = (JwtUser) authentication.getPrincipal();
        String username = principal.getUsername();
        Discuss discuss = new Discuss(kid,username,content);

        int su = discussService.adByKnowledge(discuss);
        if(su == 1){
            return new Result<>(true,StatusCode.OK,"插入成功",discuss);
        }
        else{
            return null;
        }

    }

    @GetMapping("/searchKnowledgeByKeys/{keys}/{pageNum}")
    public Result<PageInfo> findByCondition(@PathVariable("keys") String condition, @PathVariable("pageNum") int pageNum){
        PageInfo pageInfo = knowledgeService.findByCondition(condition,pageNum);
        return new Result<>(true,StatusCode.OK,"查询成功",pageInfo);
    }


    @GetMapping("/getDiscussAvatar/{id}")
    public Result<List<String>> getAvatar(@PathVariable("id") Integer id){
        return new Result<>(true,StatusCode.OK,"success", knowledgeService.getAvatar(id));
    }
}
